package cn.xzqwjw.taskmanager.service.impl;

import cn.xzqwjw.taskmanager.common.customEnum.ResponseCodeEnum;
import cn.xzqwjw.taskmanager.common.exception.CustomException;
import cn.xzqwjw.taskmanager.domain.pojo.SysPurviewRoute;
import cn.xzqwjw.taskmanager.domain.vo.ResponseVo;
import cn.xzqwjw.taskmanager.repository.SysPurviewRouteMapper;
import cn.xzqwjw.taskmanager.service.SysPurviewRouteService;
import cn.xzqwjw.taskmanager.utils.JsonUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @author rush
 */
@Service("SysPurviewRouteService")
@Transactional(rollbackFor = Exception.class)
public class SysPurviewRouteServiceImpl extends ServiceImpl<SysPurviewRouteMapper, SysPurviewRoute>
    implements SysPurviewRouteService {

  @Override
  public String add(SysPurviewRoute sysPurviewRoute) {
    if (save(sysPurviewRoute)) {
      return JsonUtil.obj2Json(ResponseVo.success(ResponseCodeEnum.OK_CREATED));
    } else {
      throw new CustomException(ResponseCodeEnum.ERROR_INSERT);
    }
  }

  @Override
  public String modifyRouteIdByPurviewId(Integer idPurview, Integer idRoute) {
    UpdateWrapper<SysPurviewRoute> wrapper = new UpdateWrapper<>();
    wrapper.set("id_route", idRoute).eq("id_purview", idPurview);
    if (update(wrapper)) {
      return JsonUtil.obj2Json(ResponseVo.success(ResponseCodeEnum.OK_UPDATED));
    } else {
      throw new CustomException(ResponseCodeEnum.ERROR_UPDATE);
    }
  }

  @Override
  public String getRouteIdByPurviewId(Integer idPurview) {
    QueryWrapper<SysPurviewRoute> wrapper = new QueryWrapper<>();
    wrapper.eq("id_purview", idPurview);
    SysPurviewRoute purviewRoute = getOne(wrapper);
    int idRoute = Objects.nonNull(purviewRoute) ? purviewRoute.getIdRoute() : 1;
    return JsonUtil.obj2Json(ResponseVo.success(idRoute));
  }

}
